<template>
  <div class="container dark-theme">
    <!-- 头部导航栏 -->
    <div class="header">
      <div class="logo">“沈誉通”信用生活综合系统</div>
      <div class="nav">
        <!-- <router-link to="/home">首页</router-link> -->
        <router-link to="/credit-life">信用生活</router-link>
        <router-link to="/credit-business">信用商业</router-link>
        <router-link to="/behavior">亲社会行为</router-link>
        <router-link to="/news">新闻资讯</router-link>
        <router-link to="/credit-management">信用管理</router-link>
      </div>
      <div class="user-menu" ref="userMenu">
        <div class="notification">
          <router-link to="/notice">
            <i class="el-icon-message"></i>
          </router-link>
        </div>
        <div class="avatar-box">
          <img
            :src="user.icon"
            class="avatar"
            alt="用户头像"
            @click.stop="toggleMenu"
          />
        </div>
        <div v-if="isMenuOpen" class="dropdown-menu">
          <div class="menu-item" @click="goToProfile">个人信息</div>
          <div class="menu-item" @click="logout">退出登录</div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 上方界面 -->
      <div class="top-section">
        <!-- 左侧信用分数展示 -->
        <div class="credit-score-section">
          <div class="score-circle">
            <div class="circle-progress" :style="{ '--percentage': progressPercentage }">
              <div class="circle-progress-inner">
                <div class="score">{{ user.score }}</div>
                <div class="label">信用分</div>
              </div>
            </div>
          </div>
          <div class="credit-level">
            <div class="current-level">当前信用等级为V{{ user.score/100 }}</div>
            <div class="progress-bar">
              <div class="progress" :style="{ width: progressPercentage + '%' }"></div>
            </div>
            <div class="next-level">还需{{ 100-user.score%100 }}信用值可升级至V{{  user.score/100 + 1 }}</div>
            <div class="debug-info">进度: {{ user.score%100 }}%</div>
          </div>
        </div>

        <!-- 分隔线 -->
        <div class="divider vertical"></div>

        <!-- 右侧功能按钮网格 -->
        <div class="function-grid">
          <div class="section-title">可享信用服务</div>
          <!-- 第一行：信用生活服务 -->
          <div class="grid-row">
            <div class="grid-item" @click="navigateTo('credit-life')">
              <i class="el-icon-reading"></i>
              <span>图书借阅</span>
            </div>
            <div class="grid-item" @click="navigateTo('credit-life')">
              <i class="el-icon-first-aid-kit"></i>
              <span>舒心就医</span>
            </div>
            <div class="grid-item" @click="navigateTo('credit-life')">
              <i class="el-icon-truck"></i>
              <span>便接驳车</span>
            </div>
            <div class="grid-item" @click="navigateTo('credit-life')">
              <i class="el-icon-connection"></i>
              <span>公共交通</span>
            </div>
          </div>
          <!-- 第二行：信用商业服务 -->
          <div class="grid-row">
            <div class="grid-item" @click="navigateTo('credit-business/products')">
              <i class="el-icon-shopping-bag-1"></i>
              <span>商品购买</span>
            </div>
            <div class="grid-item" @click="navigateTo('credit-business/houses')">
              <i class="el-icon-house"></i>
              <span>房屋租赁</span>
            </div>
            <div class="grid-item" @click="navigateTo('credit-business/rooms')">
              <i class="el-icon-office-building"></i>
              <span>酒店预订</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 分隔线 -->
      <div class="divider horizontal"></div>

      <!-- 下方界面 -->
      <div class="bottom-section">
        <!-- 守约记录 -->
        <div class="record-section">
          <h3 class="section-title">守约记录</h3>
          <el-table :data="promiseRecords" style="width: 100%" class="custom-table">
            <el-table-column prop="serviceType" label="使用服务类型" width="600"></el-table-column>
            <el-table-column prop="serviceDesc" label="服务描述" width="600"></el-table-column>
            <el-table-column prop="status" label="状态" width="600">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === '已完成' ? 'success' : 'warning'">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 行为积累 -->
        <div class="behavior-section">
          <h3 class="section-title">行为积累</h3>
          <div class="behavior-stats">
            <div class="stat-card">
              <div class="stat-icon">
                <i class="el-icon-date"></i>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ behaviorStats.days }}</div>
                <div class="stat-label">守信累计天数</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon">
                <i class="el-icon-service"></i>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ behaviorStats.lifeTimes }}</div>
                <div class="stat-label">信用生活使用次数</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon">
                <i class="el-icon-shopping-bag-1"></i>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ behaviorStats.business_times }}</div>
                <div class="stat-label">信用商业使用次数</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon">
                <i class="el-icon-star-on"></i>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ behaviorStats.behavior_times }}</div>
                <div class="stat-label">亲社会行为使用次数</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'CreditManagement',
  data() {
    return {
      user: {},
      isMenuOpen: false,
      imageBaseUrl: 'http://localhost:8089',
      promiseRecords: [],
      behaviorStats: {
        days: 0,
        lifeTimes: 0,
        business_times: 0,
        behavior_times: 0
      },
      isFetchingOrders: false
    }
  },
  created() {
    this.queryUser();
    this.fetchBehaviorStats();
  },
  computed: {
    progressPercentage() {
      const level = Math.floor(this.user.score / 100) + 1;
      const currentLevelMin = (level - 1) * 100;
      const currentLevelMax = level * 100;
      const currentLevelProgress = this.user.score - currentLevelMin;
      const levelRange = currentLevelMax - currentLevelMin;
      const percentage = Math.min(Math.max((currentLevelProgress / levelRange) * 100, 0), 100);
      return percentage;
    },
    calculatedCreditLevel() {
      return Math.floor(this.user.score / 100) + 1;
    },
    nextLevelScore() {
      return this.calculatedCreditLevel * 100;
    }
  },
  methods: {
    toggleMenu() {
      this.isMenuOpen = !this.isMenuOpen;
    },
    closeMenuOnClickOutside(event) {
      const menu = this.$refs.userMenu;
      if (menu && !menu.contains(event.target)) {
        this.isMenuOpen = false;
      }
    },
    goToProfile() {
      this.$router.push('/user-information');
      this.isMenuOpen = false;
    },
    logout() {
      axios.post('/user/logout')
        .then(() => {
          sessionStorage.removeItem('token');
          this.$router.push('/');
        })
        .catch(err => console.error('退出登录失败:', err.message));
    },
    async queryUser() {
      try {
        const response = await axios.get('/users/user/me', {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        if (response.data.success && response.data.data) {
          this.user = response.data.data;
          if (this.user.icon && !this.user.icon.startsWith('http')) {
            this.user.icon = `${this.imageBaseUrl}${this.user.icon}`;
          }
          this.queryUserInfo();
          this.waitForUserId();
        }
      } catch (err) {
        console.error('获取用户信息失败:', err.message);
      }
    },
    queryUserInfo() {
      axios.get(`/users/user/basic`)
        .then(({ data }) => {
          this.info = data || { introduce: '' };
          sessionStorage.setItem('userInfo', JSON.stringify(data));
        })
        .catch(err => console.error('获取用户基本信息失败:', err.message));
    },
    navigateTo(route) {
      this.$router.push(`/${route}`);
    },
    waitForUserId() {
      if (this.isFetchingOrders || this.user.id) {
        if (this.user.id) {
          this.fetchAllOrders();
          this.fetchBehaviorStats();
        }
        return;
      }
      const checkInterval = setInterval(() => {
        if (this.user.id) {
          clearInterval(checkInterval);
          this.fetchAllOrders();
          this.fetchBehaviorStats();
        }
      }, 100);
    },
    async fetchBehaviorStats() {
      if (!this.user.id) {
        console.warn('跳过行为统计请求，userId 未定义');
        return;
      }
      try {
        const response = await axios.get(`/users/accumulation/${this.user.id}`, {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        if (response.data.success && response.data.data) {
          this.behaviorStats = {
            days: response.data.data.days || 0,
            lifeTimes: response.data.data.lifeTimes || 0,
            business_times: response.data.data.businessTimes || 0,
            behavior_times: response.data.data.behaviorTimes || 0
          };
        }
      } catch (err) {
        console.error('获取行为统计失败:', err.message);
        this.behaviorStats = {
          days: 0,
          lifeTimes: 0,
          business_times: 0,
          behavior_times: 0
        };
      }
    },
    async fetchAllOrders() {
      if (this.isFetchingOrders || !this.user.id) {
        return;
      }
      this.isFetchingOrders = true;
      const userId = this.user.id;
      const token = localStorage.getItem('token');
      const headers = { Authorization: `Bearer ${token}` };
      try {
        const houseOrders = await this.fetchOrders('/commodity/house-order/list/allOrder', userId, headers, '房屋租赁');
        const goodOrders = await this.fetchOrders('/commodity/good-order/list/allOrder', userId, headers, '商品购买');
        const roomOrders = await this.fetchOrders('/commodity/room-order/list/allOrder', userId, headers, '酒店预订');
        const activityOrders = await this.fetchOrders('/commodity/activity-order/list/allOrder', userId, headers, '亲社会活动');
        this.promiseRecords = [...houseOrders, ...goodOrders, ...roomOrders, ...activityOrders];
      } catch (error) {
        console.error('获取守约记录失败:', error);
      } finally {
        this.isFetchingOrders = false;
      }
    },
    async fetchOrders(url, userId, headers, serviceType) {
      if (!userId) {
        console.warn(`跳过${serviceType}请求，userId 未定义`);
        return [];
      }
      try {
        const response = await axios.get(`${url}?userId=${userId}`, { headers });
        if (response.data.success && response.data.data?.length > 0) {
          return response.data.data.map(order => ({
            serviceType,
            serviceDesc: this.getServiceDesc(serviceType, order),
            status: this.getStatusText(serviceType, order.status)
          }));
        }
        return [];
      } catch (error) {
        console.error(`获取${serviceType}订单失败:`, error);
        return [];
      }
    },
    getServiceDesc(serviceType, order) {
      switch (serviceType) {
        case '房屋租赁':
          return `租赁${order.title || '未知房屋'}，${order.amount}个月`;
        case '商品购买':
          return `购买${order.title || '未知商品'}，数量${order.amount}`;
        case '酒店预订':
          return `预订${order.title || '未知房间'}，${order.amount}天`;
        case '亲社会活动':
          return `参与${order.title || '未知活动'}`;
        default:
          return '未知服务';
      }
    },
    getStatusText(serviceType, status) {
      if (serviceType === '亲社会活动') {
        switch (status) {
          case 1: return '已报名';
          case 2: return '已取消';
          default: return '未知';
        }
      }
      if (serviceType === '酒店预订') {
        switch (status) {
          case 1: return '已预订';
          case 2: return '已取消';
          default: return '未知';
        }
      }
      if (serviceType === '商品购买') {
        switch (status) {
          case 1: return '已购买';
          case 2: return '已退款';
          default: return '未知';
        }
      }
      if (serviceType === '房屋租赁') {
        switch (status) {
          case 1: return '已租赁';
          case 2: return '已取消';
          default: return '未知';
        }
      }
    }
  }
}
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: radial-gradient(ellipse at center, #001e3c 0%, #000 100%);
  color: #fff;
  font-family: 'Microsoft YaHei', sans-serif;
}

.header {
  display: flex;
  justify-content: space-between;
  padding: 10px 30px;
  background: #002d52;
  align-items: center;
  border-bottom: none;
}

.logo {
  font-size: 20px;
  color: #4fc3f7;
}

.nav {
  display: flex;
  margin-left: auto;
  margin-right: auto;
}

.nav a {
  margin: 0 10px;
  color: #fff;
  text-decoration: none;
}

.nav a:hover {
  text-decoration: none;
  color: #4fc3f7;
}

.user-menu {
  position: relative;
  display: flex;
  align-items: center;
}

.notification {
  margin-right: 10px;
}

.notification a {
  color: #fff;
  text-decoration: none;
}

.notification i {
  font-size: 24px;
  color: #4fc3f7;
}

.notification i:hover {
  color: #2196f3;
}

.avatar-box img.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #4fc3f7;
}

.dropdown-menu {
  position: absolute;
  top: 50px;
  right: 0;
  width: 120px;
  background: #002d52;
  border: 1px solid #4fc3f7;
  border-radius: 4px;
  z-index: 10;
  box-shadow: none;
}

.menu-item {
  padding: 10px;
  border-bottom: none;
  color: #fff;
  font-size: 14px;
  cursor: pointer;
}

.menu-item:hover {
  background: #014b75;
}

.main-content {
  padding: 20px;
}

.top-section {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.credit-score-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  background: rgba(0, 45, 82, 0.8);
  border-radius: 8px;
}

.score-circle {
  width: 200px;
  height: 200px;
  margin-bottom: 20px;
}

.circle-progress {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background: conic-gradient(#4fc3f7 0deg calc(var(--percentage) * 3.6deg), #003b64 calc(var(--percentage) * 3.6deg) 360deg);
  display: flex;
  align-items: center;
  justify-content: center;
}

.circle-progress-inner {
  width: 90%;
  height: 90%;
  background: #002d52;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.score {
  font-size: 36px;
  font-weight: bold;
  color: #4fc3f7;
}

.label {
  font-size: 16px;
  color: #b0bec5;
}

.credit-level {
  width: 100%;
  text-align: center;
}

.current-level {
  font-size: 18px;
  color: #4fc3f7;
  margin-bottom: 10px;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: #e0e0e0;
  border-radius: 4px;
  margin: 10px 0;
  overflow: hidden;
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.2);
  position: relative;
}

.progress {
  height: 100%;
  background: linear-gradient(90deg, #4fc3f7, #2196f3);
  border-radius: 4px;
  transition: width 0.3s ease;
  box-shadow: 0 1px 3px rgba(79, 195, 247, 0.3);
  position: absolute;
  top: 0;
  left: 0;
}

.next-level {
  font-size: 14px;
  color: #b0bec5;
}

.debug-info {
  font-size: 12px;
  color: #4fc3f7;
  margin-top: 5px;
}

.function-grid {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  background: rgba(0, 45, 82, 0.8);
  border-radius: 8px;
}

.section-title {
  font-size: 18px;
  color: #4fc3f7;
  margin-bottom: 15px;
  text-align: center;
}

.grid-row {
  display: flex;
  gap: 20px;
  justify-content: space-between;
}

.grid-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background: #003b64;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.grid-item:hover {
  background: #004b7a;
  transform: translateY(-2px);
}

.grid-item i {
  font-size: 32px;
  color: #4fc3f7;
  margin-bottom: 10px;
}

.grid-item span {
  font-size: 14px;
  color: #fff;
}

.divider {
  background: #003b64;
}

.divider.vertical {
  width: 2px;
  height: auto;
}

.divider.horizontal {
  height: 2px;
  width: 100%;
  margin: 20px 0;
}

.bottom-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.record-section,
.behavior-section {
  background: rgba(0, 45, 82, 0.8);
  border-radius: 8px;
  padding: 20px;
}

.record-section .section-title,
.behavior-section .section-title {
  text-align: left;
  margin-bottom: 20px;
}

.custom-table {
  background: transparent;
}

:deep(.el-table) {
  background: transparent;
  color: #000;
}

:deep(.el-table th) {
  background: #003b64;
  color: #4fc3f7;
  border-bottom: 1px solid #4fc3f7;
}

:deep(.el-table td) {
  background: #fff;
  color: #000;
  border-bottom: 1px solid #003b64;
}

:deep(.el-table--border) {
  border: 1px solid #003b64;
}

.behavior-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  justify-content: space-between;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #003b64;
  border-radius: 8px;
  border: 1px solid #4fc3f7;
}

.stat-icon {
  margin-right: 15px;
}

.stat-icon i {
  font-size: 32px;
  color: #4fc3f7;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #4fc3f7;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #b0bec5;
}

:deep(.el-tag--success) {
  background: #67c23a;
  border-color: #67c23a;
  color: #fff;
}

:deep(.el-tag--warning) {
  background: #e6a23c;
  border-color: #e6a23c;
  color: #fff;
}
</style>
